import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

import { getCurrentDate,initList } from '@/function'

export const useCalendarStore = defineStore('calendar', () => {
  // 当前日期
  const currentDate = getCurrentDate()

  // 选中日期
  const selectedDate = ref(currentDate)

  // 选中的年
  const selectedYear = computed({
    get: () => selectedDate.value.year,
    set: (value) => {
      selectedDate.value.year = value
    },
  })

  // 选中的月
  const selectedMonth = computed({
    get: () => selectedDate.value.month,
    set: (value) => {
      selectedDate.value.month = value
    },
  })

  // 选中的日
  const selectedDay = computed({
    get: () => selectedDate.value.day,
    set: (value) => {
      selectedDate.value.day = value
    },
  })

  const lastMonth = () => {
      if (selectedMonth.value <= 1) {
        selectedYear.value--
        selectedMonth.value = 12
      } else {
        selectedMonth.value--
      }
    }
  
    const nextMonth = () => {
      if (selectedMonth.value >= 12) {
        selectedYear.value++
        selectedMonth.value = 1
      } else {
        selectedMonth.value++
      }
    }

  const gotoToday = () => {
    selectedDate.value = getCurrentDate()
  }

  const lists = computed(() => {
    return initList(selectedYear.value, selectedMonth.value)
  })

  const formatDate = computed(() => {
    return `${selectedYear.value}-${selectedMonth.value}-${selectedDay.value}`
  })
  return {
    selectedYear,
    selectedMonth,
    selectedDay,
    lists,
    lastMonth,
    nextMonth,
    gotoToday,
    formatDate,
  }
})
